from typing import Optional
from pydantic import BaseModel, Field, HttpUrl
from fastapi import FastAPI, Query, Path, Body

app = FastAPI()

data = ['AA', 'BB', 'CC']


class Image(BaseModel):
    url: HttpUrl
    name: str


class Item(BaseModel):
    name: str
    price: float = Field(..., gt=0, description='价格必须大于0')
    description: Optional[str] = Field(None, title='这是介绍', max_length=300)
    tax: Optional[float] = None
    sellarea: list[str] = []
    image: Optional[Image] = None


class User(BaseModel):
    username: str
    year: str


@app.put("/items/{itemid}")
async def update_item(itemid: int, item: Item = Body(..., embed=True)):
    results = {"itemid": itemid, "item": item}
    return results


@app.put("/items")
def update_item(item: Optional[Item], user: User, sell: str = Body(...)):
    result = {}
    if item.tax is not None:
        total = item.price * item.tax
        result['price'] = total
        result['name'] = item.name
        result['user'] = user
        result['sell'] = sell
        return result
    result['price'] = item.price
    result['name'] = item.name
    result['user'] = user
    result['sell'] = sell
    return result


@app.get("/")
async def root():
    return {"message": "Hello gwp"}


@app.get("/hello/{name}")
async def say_hello(name: str):
    return {"message": f"Hello {name}"}


@app.get("/items")
def read_item(start: int, end: Optional[int] = None):
    if end:
        return data[start:end]
    return data[start:]


@app.post("/items")
def create_item(item: Item):
    if item.price > 100:
        return "太贵了"
    return item


# @app.get("/result")
# def update_items(m: Optional[str] = Query(None,regex='^name', max_length=10, min_length=5)):
#     results = {"items": [{"oneid": "shanghai"}, {"two": "beijing"}]}
#     if m:
#         results.update({"shanghai": m})
#     return results

# @app.get("/result")
# def read(paword: str = Query(..., min_length=8, max_length=16)):
#     results = {"items": [{"oneid": "shanghai"}, {"two": "beijing"}]}
#     if paword:
#         results.update({"paword": paword})
#     return results

@app.get("/result")
def read(paword: Optional[list[str]] = Query(None)):
    results = {"items": [{"oneid": "shanghai"}, {"two": "beijing"}]}
    if paword:
        results.update({"paword": paword})
    return results


@app.get("/result/{id}")
def read_result(
        id: int = Path(..., title="id"),
        q: Optional[str] = Query(None, alias="item-query"),
):
    results = {"item_id": id}
    if q:
        results.update({"q": q})
    return results
